# -*- coding: utf-8 -*-
"""
用户相关路由
@api-version: 1.0.0
REF: API-USER-001~002
"""

from flask import Blueprint, request, g
from marshmallow import ValidationError
from backend.models.user import User
from backend.models.session import UserSession
from backend.schemas.user_schemas import UserUpdateSchema
from backend.utils.response import success_response, error_response, validation_error_response
from backend.utils.auth import token_required
from backend.models import db

user_bp = Blueprint('user', __name__)

@user_bp.route('/user/profile', methods=['GET'])
@token_required
def get_profile():
    """获取当前用户信息
    REF: API-USER-001
    """
    try:
        return success_response(
            data=g.current_user.to_dict(),
            message='获取用户信息成功'
        )
        
    except Exception as e:
        return error_response('获取用户信息失败', 500)

@user_bp.route('/user/me', methods=['GET'])
@token_required
def get_current_user():
    """获取当前用户信息（别名接口）
    REF: API-USER-001
    """
    try:
        return success_response(
            data=g.current_user.to_dict(),
            message='获取用户信息成功'
        )
        
    except Exception as e:
        return error_response('获取用户信息失败', 500)

@user_bp.route('/user/me', methods=['PUT'])
@token_required
def update_current_user():
    """更新当前用户信息（别名接口）
    REF: API-USER-002
    """
    try:
        # 数据验证
        schema = UserUpdateSchema()
        data = schema.load(request.get_json() or {})
        
        user = g.current_user
        
        # 检查昵称唯一性和修改限制
        if 'nickname' in data and data['nickname'] != user.nickname:
            # 检查昵称唯一性
            existing_user = User.query.filter_by(nickname=data['nickname']).first()
            if existing_user:
                return error_response('昵称已被使用', 400)
            
            # 检查昵称修改限制（每年一次）
            if not user.can_update_nickname():
                return error_response('昵称每年只能修改一次', 400)
            
            # 更新昵称
            user.update_nickname(data['nickname'])
            del data['nickname']  # 从data中移除，避免重复设置
        
        # 更新其他用户信息（邮箱不可修改）
        for field, value in data.items():
            if hasattr(user, field) and field != 'email':
                setattr(user, field, value)
        
        db.session.commit()
        
        return success_response(
            data=user.to_dict(),
            message='用户信息更新成功'
        )
        
    except ValidationError as e:
        return validation_error_response(e.messages)
    except Exception as e:
        return error_response('用户信息更新失败', 500)

@user_bp.route('/user/profile', methods=['PUT'])
@token_required
def update_profile():
    """更新当前用户信息
    REF: API-USER-002
    """
    try:
        # 数据验证
        schema = UserUpdateSchema()
        data = schema.load(request.get_json() or {})
        
        user = g.current_user
        
        # 检查昵称唯一性和修改限制
        if 'nickname' in data and data['nickname'] != user.nickname:
            # 检查昵称唯一性
            existing_user = User.query.filter_by(nickname=data['nickname']).first()
            if existing_user:
                return error_response('昵称已被使用', 400)
            
            # 检查昵称修改限制（每年一次）
            if not user.can_update_nickname():
                return error_response('昵称每年只能修改一次', 400)
            
            # 更新昵称
            user.update_nickname(data['nickname'])
            del data['nickname']  # 从data中移除，避免重复设置
        
        # 更新其他用户信息（邮箱不可修改）
        for field, value in data.items():
            if hasattr(user, field) and field != 'email':
                setattr(user, field, value)
        
        db.session.commit()
        
        return success_response(
            data=user.to_dict(),
            message='用户信息更新成功'
        )
        
    except ValidationError as e:
        return validation_error_response(e.messages)
    except Exception as e:
        return error_response('用户信息更新失败', 500)

@user_bp.route('/user/password', methods=['PUT'])
@token_required
def change_password():
    """修改密码
    REF: API-USER-003
    """
    try:
        data = request.get_json() or {}
        old_password = data.get('oldPassword')
        new_password = data.get('newPassword')
        
        if not old_password or not new_password:
            return error_response('旧密码和新密码不能为空', 400)
        
        user = g.current_user
        
        # 验证旧密码
        if not user.check_password(old_password):
            return error_response('旧密码错误', 400)
        
        # 验证新密码格式
        if len(new_password) < 6:
            return error_response('新密码长度不能少于6位', 400)
        
        # 更新密码
        user.set_password(new_password)
        db.session.commit()
        
        # 清除该用户的所有会话（强制重新登录）
        UserSession.query.filter_by(user_id=user.id).delete()
        db.session.commit()
        
        return success_response(message='密码修改成功，请重新登录')
        
    except Exception as e:
        return error_response('密码修改失败', 500)

@user_bp.route('/user/sessions', methods=['GET'])
@token_required
def get_user_sessions():
    """获取当前用户的会话列表
    REF: API-USER-004
    """
    try:
        from backend.models.session import UserSession
        
        sessions = UserSession.query.filter_by(
            user_id=g.current_user.id
        ).order_by(UserSession.created_at.desc()).all()
        
        # 清理过期会话
        expired_sessions = [s for s in sessions if s.is_expired()]
        for session in expired_sessions:
            db.session.delete(session)
        
        if expired_sessions:
            db.session.commit()
            # 重新查询有效会话
            sessions = UserSession.query.filter_by(
                user_id=g.current_user.id
            ).order_by(UserSession.created_at.desc()).all()
        
        sessions_data = []
        for session in sessions:
            session_dict = session.to_dict()
            session_dict['isCurrent'] = session.id == g.current_session.id
            # 不返回完整token，只返回部分用于识别
            session_dict['token'] = session.token[:8] + '...' + session.token[-8:]
            sessions_data.append(session_dict)
        
        return success_response(
            data=sessions_data,
            message='获取会话列表成功'
        )
        
    except Exception as e:
        return error_response('获取会话列表失败', 500)

@user_bp.route('/user/sessions/<int:session_id>', methods=['DELETE'])
@token_required
def delete_user_session(session_id):
    """删除指定会话
    REF: API-USER-005
    """
    try:
        from backend.models.session import UserSession
        
        session = UserSession.query.filter_by(
            id=session_id,
            user_id=g.current_user.id
        ).first()
        
        if not session:
            return error_response('会话不存在', 404)
        
        # 不能删除当前会话
        if session.id == g.current_session.id:
            return error_response('不能删除当前会话', 400)
        
        db.session.delete(session)
        db.session.commit()
        
        return success_response(message='会话删除成功')
        
    except Exception as e:
        return error_response('会话删除失败', 500)